<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { fetchCaptchaAPI, sendEmailCaptchaAPI, register } from '@/api/index.js'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const account = ref('')
const passWord = ref('')
const captcha = ref('')
const captchaUrl = ref('')
const showLogin = ref(false)
const showRegister = ref(false)

// 注册表单字段
const registerForm = ref({
  account: '',
  passWord: '',
  email: '',
  captcha: ''
})

// 计时器状态
const isCounting = ref(false)
const countdown = ref(120)

// 切换到登录弹窗并清空输入
const showLoginfunction = () => {
  account.value = ''
  passWord.value = ''
  captcha.value = ''
  showLogin.value = true
}

const registerToLogin = () => {
  showRegister.value = false;
  showLogin.value = true;
  isCounting.value = false;
  registerForm.username = '';
  registerForm.registerPassword = '';
  registerForm.email = '';
  registerForm.emailCaptcha = ' ';
}
// 获取验证码图片
const refreshCaptcha = async () => {
  captchaUrl.value = await fetchCaptchaAPI()
}

// 登录逻辑
const handleLogin = async () => {
  const userData = { account: account.value, passWord: passWord.value, captcha: captcha.value }
  await userStore.login(userData)
}

// 发送邮箱验证码并启动倒计时
const sendEmailCaptcha = async (email) => {
  if (!email) {
    ElMessage.error('请输入邮箱')
    return
  }
  try {
    await sendEmailCaptchaAPI(email)
    ElMessage.success('验证码发送成功')
    isCounting.value = true
    countdown.value = 120

    const timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--
      } else {
        clearInterval(timer)
        isCounting.value = false
      }
    }, 1000)
  } catch (error) {
    ElMessage.error('验证码发送失败')
    console.error('发送验证码失败:', error)
  }
}

// 注册逻辑
const handleRegister = async () => {
  try {
    const response = await register(registerForm.value)
    if (response.data.code === 200) {
      ElMessage.success('注册成功')
      showRegister.value = false
      showLogin.value = true
      registerForm.value = {
        username: '',
        registerPassword: '',
        email: '',
        emailCaptcha: ''
      }
    } else {
      ElMessage.error('注册失败')
    }
  } catch (error) {
    ElMessage.error('注册请求失败')
    console.error('注册失败:', error)
  }
}

// 页面加载时刷新验证码
refreshCaptcha()
</script>


<template>
  <div >
    <img src="@/assets/photo/江景.png" alt="背景图" style="width: 100%; height: 100%; position: absolute; top: 0; left: 0; opacity: 0.9;">
  </div>


  <div class="title" >
    学生项目管理系统
  </div>
<!--  网站介绍-->

    <div style="position: relative;margin-left: 50px;margin-top:150px;font-size: 20px; color: #cbe3f8">
      <p>我们的口号：“让学习变得更有趣！，让项目管理更简单！，让学习更有价值！”</p>
      <p style="margin-top: 20px;">
        在这里你可以轻松管理项目、跟踪进度、分享心得、交流想法，充实你的大学生活，识交良师益友
      </p>
      </div>

  <img src="@/assets/photo/奋斗.png" alt="" style="position: relative;width: 65%;margin-left: 30%;margin-top: 30px;border-radius:10%;" >


    <!-- 登录按钮 -->
    <el-button type="primary" @click="showLoginfunction" style="position: absolute; top: 10px; right: 10px;">登录</el-button>

    <!-- 登录弹窗 -->
    <el-dialog title="登录" v-model="showLogin" width="30%">
      <el-form @submit.native.prevent="handleLogin">
        <!-- 账号输入框 -->
        <el-form-item prop="account" :rules="[{ pattern: /^[\x00-\x7F]+$/, message: '仅支持ASCII字符', trigger: 'blur' }]">
          <el-input v-model="account" placeholder="账号" />
        </el-form-item>

        <!-- 密码输入框 -->
        <el-form-item prop="password" :rules="[{ pattern: /^[\x00-\x7F]+$/, message: '仅支持ASCII字符', trigger: 'blur' }]">
          <el-input v-model="passWord" type="password" placeholder="密码" show-password />
        </el-form-item>

        <!-- 验证码输入框 -->
        <el-form-item prop="captcha" :rules="[{ pattern: /^[\x00-\x7F]+$/, message: '仅支持ASCII字符', trigger: 'blur' }]">
          <el-row gutter="10">
            <el-col :span="16">
              <el-input v-model="captcha" placeholder="验证码" />
            </el-col>
            <el-col :span="8">
              <img :src="captchaUrl" alt="验证码" @click="refreshCaptcha" style="cursor: pointer;" />
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-button  style="margin-left:25%;width: 200px;" type="primary" @click="handleLogin">登录</el-button>
        <div style="margin-top: 10px;">
          <span @click="showRegister = true; showLogin = false" style="margin-left: 10px; cursor: pointer;color: #a1a1a1">还没有账号？立即注册</span>
        </div>
      </el-form>
    </el-dialog>

    <!-- 注册弹窗 -->
    <el-dialog title="注册" v-model="showRegister" width="30%">
      <el-form @submit.native.prevent="handleRegister">
        <!-- 用户名输入框 -->
        <el-form-item prop="username" :rules="[{ pattern: /^[\x00-\x7F]+$/, message: '仅支持ASCII字符', trigger: 'blur' }]">
          <el-input v-model="registerForm.account" placeholder="账号" />
        </el-form-item>

        <!-- 密码输入框 -->
        <el-form-item prop="registerPassword" :rules="[{ pattern: /^[\x00-\x7F]+$/, message: '仅支持ASCII字符', trigger: 'blur' }]">
          <el-input v-model="registerForm.passWord" type="password" placeholder="密码" show-password />
        </el-form-item>

        <!-- 邮箱输入框和发送验证码按钮 -->
        <el-form-item prop="email" :rules="[{ pattern: /^[\x00-\x7F]+$/, message: '仅支持ASCII字符', trigger: 'blur' }]">
          <el-row gutter="10">
            <el-col :span="16">
              <el-input v-model="registerForm.email" placeholder="邮箱" />
            </el-col>
            <el-col :span="8">
              <el-button :disabled="isCounting" @click="sendEmailCaptcha(registerForm.email)">
                {{ isCounting ? `${countdown}秒` : '发送验证码' }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 验证码输入框 -->
        <el-form-item prop="emailCaptcha" :rules="[{ pattern: /^[\x00-\x7F]+$/, message: '仅支持ASCII字符', trigger: 'blur' }]">
          <el-input v-model="registerForm.captcha" placeholder="邮箱验证码" />
        </el-form-item>

        <!-- 注册按钮 -->
        <el-button type="primary" style="margin-left:25%;width: 200px;"  @click="handleRegister">注册</el-button>
        <div style="margin-top: 10px;">
          <span @click="registerToLogin" style="margin-left: 10px; cursor: pointer;color: #a1a1a1">已有账号？前往登录</span>
        </div>
      </el-form>
    </el-dialog>
</template>



<style scoped>
.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}
.title {
  position: relative;
  font-size: 34px;
  font-weight: bold;
  text-align: center;
  color: #cbe3f8;
  margin-top: -40px;
  margin-left: -500px;
}
</style>
